package com.appspot.seqpop.controller;

import org.slim3.controller.Navigation;
import org.slim3.util.RequestMap;

import com.appspot.seqpop.model.Alignment;
import com.appspot.seqpop.model.Result;
import com.appspot.seqpop.service.StoreService;
import com.appspot.seqpop.service.UpdateService;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class StoreController extends SeqpopController {

    StoreService service = new StoreService();
    UpdateService update = new UpdateService();

    @Override
    public Navigation run() throws Exception {
        Key key = null;

        if (isPost() && param("fasta") != null) {
            key = this.service.create(new RequestMap(this.request));
        } else {
            key = asKey("key");
        }

        if (key == null) {
            throw new Exception("Key is not defined.");
        }

        if (isDelete()) {
            this.service.delete(key);
            return redirect("/");
        }

        Alignment alignment = this.service.read(key);
        updateResult(alignment.getKey());

        if (param("view") != null && asBoolean("view") == false) {
            Object json = alignment.asJson();
            output(json);
            return null;
        }

        requestScope("alignment", alignment.getAlignment());
        requestScope("key", KeyFactory.keyToString(alignment.getKey()));
        requestScope("createdDate", alignment.getCreatedDate());
        requestScope("lastModifiedDate", alignment.getLastModifiedDate());
        requestScope("length", alignment.getLength());
        requestScope("count", alignment.getSequenceCount());

        Result result = alignment.getResultRef().getModel();
        requestScope("segregatingSites", result.getSegregatingSites());
        requestScope("nucleotideDifferences", result.getNucleotideDifferences());
        requestScope("tajimaD", result.getTajimaD());
        requestScope("fuAndLiDStar", result.getFuAndLiDStar());
        requestScope("fuAndLiFStar", result.getFuAndLiFStar());

        return forward("/store.jsp");
    }
    
    private void updateResult(Key key) {
        String[] statistics = paramValues("statistic");
        if (statistics != null && statistics.length > 0) {
            UpdateService.Updater[] updaters = new UpdateService.Updater[statistics.length];
            for (int index = 0; index < statistics.length; index++) {
                updaters[index] = update.getUpdater(statistics[index]);
            }
            update.update(key, updaters);
        }
    }
}
